package com.bt.att;

import com.bt.att.dao.PhoneDao;
import com.bt.att.model.Phone;
import org.springframework.beans.factory.annotation.Autowired;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.*;
import java.util.List;

public class ToolbarJPanel extends JPanel implements ActionListener {
    private static final String CALL = "Calls";
    private static final String MESSAGE = "Messages";

    private TableDataScrollPane tablePane;
    private int axis;

    private Map<String, Phone> nameToPhones = new HashMap<String, Phone>();
    private JComboBox comboBox;
    private JRadioButton callButton;
    private JRadioButton messageButton;

    @Autowired
    private PhoneDao dao;

    public void setAxis(int axis) {
        this.axis = axis;
    }

    public void setTablePane(TableDataScrollPane tablePane) {
        this.tablePane = tablePane;
    }

    public void init() {
        setLayout(new FlowLayout(axis));

        List<Phone> phones = dao.getFamilyPhones();
        nameToPhones.clear();
        List<String> list = new ArrayList<String>();
        for (Phone phone : phones) {
            list.add(phone.getPerson());
            nameToPhones.put(phone.getPerson(), phone);
        }

        comboBox = new JComboBox(list.toArray(new String[0]));
        if (list.size() > 0) {
            comboBox.setSelectedIndex(0);
        }
        comboBox.addActionListener(this);
        add(comboBox);

        callButton = new JRadioButton(CALL);
        callButton.setMnemonic(KeyEvent.VK_B);
        callButton.setActionCommand(CALL);
        callButton.setSelected(true);

        messageButton = new JRadioButton(MESSAGE);
        messageButton.setMnemonic(KeyEvent.VK_C);
        messageButton.setActionCommand(MESSAGE);

        //Group the radio buttons.
        ButtonGroup group = new ButtonGroup();
        group.add(callButton);
        group.add( messageButton);

       //Register a listener for the radio buttons.
        callButton.addActionListener(this);
        messageButton.addActionListener(this);

        add(callButton);
        add( messageButton);

        JButton refreshButton = new JButton("Refresh");
        refreshButton.addActionListener(this);
        add(refreshButton);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String person = comboBox.getSelectedItem().toString();
        Phone phone = nameToPhones.get(person);
        boolean isCall = true;
        if (messageButton.isSelected()) {
            isCall = false;
        }
        tablePane.setDataFilter(phone, isCall, null, null);
    }
}